package com.jinzhi.jzweb.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.common.controller.SchoolApittController;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.oss.service.OssService;
import jodd.io.ZipUtil;
import org.apache.http.entity.ContentType;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.domain.CertificateManagementDO;
import com.jinzhi.jzweb.service.CertificateManagementService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * <pre>
 * 第三方证书导入
 * 证书导入
 * 1+x证书导入
 * </pre>
 * <small> 2022-12-13 10:03:27 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/certificateManagement")
public class CertificateManagementController extends BaseController {
	@Autowired
	private CertificateManagementService certificateManagementService;
	@Autowired
	private SchoolApittController schoolApittController;

	@Autowired
	private OssService ossService;

//	private static String uploadFileUrl = "D:/test/"; //存放压缩包的文件路径
//	private static String unzipFileUrl = "D:/test/jy/"; //解压后的文件位置


	private static String uploadFileUrl = "/opt/certificateManagement/"; //存放压缩包的文件路径

	private static String unzipFileUrl = "/opt/certificateManagement/jy/"; //解压后的文件位置



	@GetMapping()
	@RequiresPermissions("jzweb:certificateManagement:certificateManagement")
	String CertificateManagement(){
		return "jzweb/certificateManagement/certificateManagement";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:certificateManagement:certificateManagement")
	public Result<Page<CertificateManagementDO>> list(CertificateManagementDO certificateManagementDTO){
		EntityWrapper<CertificateManagementDO> entityWrapper = new EntityWrapper();
		if (StringUtil.notEmpty(certificateManagementDTO.getIdNumber())){
			entityWrapper.eq("id_number",certificateManagementDTO.getIdNumber());
		}

		if (StringUtil.notEmpty(certificateManagementDTO.getSiteName1())){
			entityWrapper.like("site_name",certificateManagementDTO.getSiteName1());
		}
		entityWrapper.orderBy("id",false);


		// 查询列表数据
		Page<CertificateManagementDO> page = certificateManagementService.selectPage(getPage(CertificateManagementDO.class),entityWrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			CertificateManagementDO obj = (CertificateManagementDO) page.getRecords().get(i);
			list.add(obj);
		}
		page.setRecords(list);
		return Result.ok(page);
	}

	@GetMapping("/add")
	@RequiresPermissions("jzweb:certificateManagement:add")
	String add(){
		return "jzweb/certificateManagement/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:certificateManagement:edit")
	String edit(@PathVariable("id") Long id,Model model){
		CertificateManagementDO certificateManagement = certificateManagementService.selectById(id);
		model.addAttribute("certificateManagement", certificateManagement);
		return "jzweb/certificateManagement/edit";
	}

	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:certificateManagement:add")
	public Result<String> save( CertificateManagementDO certificateManagement){
		certificateManagementService.insert(certificateManagement);
		return Result.ok();
	}

	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:certificateManagement:edit")
	public Result<String>  update( CertificateManagementDO certificateManagement){
		boolean update = certificateManagementService.updateById(certificateManagement);
		return update ? Result.ok() : Result.fail();
	}

	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:certificateManagement:remove")
	public Result<String>  remove( Long id){
		certificateManagementService.deleteById(id);
		return Result.ok();
	}

	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:certificateManagement:remove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		List<CertificateManagementDO> certificateManagementDOS= new ArrayList<>();
		for (Long li :ids){
			CertificateManagementDO managementDO=new CertificateManagementDO();

			managementDO.setId(li);
			managementDO.setState(1);
			certificateManagementDOS.add(managementDO);
		}
		certificateManagementService.updateBatchById(certificateManagementDOS);
		return Result.ok();
	}


	@Log("批量删除")
	@PostMapping( "/batchRemoveDe")
	@ResponseBody
	@RequiresPermissions("jzweb:certificateManagement:remove")
	public Result<String>  batchRemoveDe(@RequestParam("ids[]") Long[] ids){

		if(this.getUsername().contains("肖正勇")||this.getUsername().contains("向晓茜")){
			boolean b =certificateManagementService.deleteBatchIds(Arrays.asList(ids));
			if(b){
				return Result.ok();
			}
		}else {
			return Result.fail("未开通权限");
		}

		return Result.fail();
	}

	@PostMapping( "/uploadCertificateManagement")
	@ResponseBody
	@Transactional
	public ApiResult<?> uploadCertificateManagement(@RequestParam("file") MultipartFile file,String certificateType,
													String siteName,String examYear){
		System.out.println("hello=================");
		int fileNum=0;
		List<CertificateManagementDO> certificateManagementDOS= new ArrayList<>();
		List<CertificateManagementDO> certificateManagementDOS1= new ArrayList<>();
		if (file.isEmpty()){
			return ApiResult.fail("文件为空");
		}
		String filename = file.getOriginalFilename(); //获取文件名称
		File dest =new File(new File(uploadFileUrl).getAbsolutePath() + "/"+filename);
		System.out.println("hello================="+dest.getName());
		try {
			file.transferTo(dest); //将目标文件上传到指定路径
			filename = uploadFileUrl + filename; //拼接文件的全路径
			UnzipUtils.unzipFile(filename, unzipFileUrl);//将文件解压到指定路径
			deleteFile(new File(uploadFileUrl)); //解压后删除压缩包

			File[] files = new File(unzipFileUrl).listFiles(); //获取所有解压后的文件
			fileNum=files.length;
			System.out.println("fileNum="+fileNum);
			//schoolApittController.yezhzssc(unzipFileUrl,getUserId().toString(),files,certificateType,siteName,examYear,openingDate);

			for (File f : files) {
				CertificateManagementDO certificateManagementDO =new CertificateManagementDO();
				String name = f.getName();
				certificateManagementDO.setName(name.substring(0, name.indexOf("("))); //截取学生姓名
				certificateManagementDO.setIdNumber(name.substring(name.indexOf("(")+1, name.indexOf(")"))); //截取身份证号码
				certificateManagementDO.setState(0); //默认证书状态为正常
				certificateManagementDO.setOperatorId(getUserId().toString()); // 操作人id
				certificateManagementDO.setCreateTime(new Date()); //创建时间
				certificateManagementDO.setCertificateType(certificateType); //类型
				certificateManagementDO.setSiteName(siteName);//考核站点名称
				certificateManagementDO.setExamYear(examYear);//考试年份
				//certificateManagementDO.setOpeningDate(openingDate); //发证日期字段

				MultipartFile mFile = null;
				File vaf = new File(unzipFileUrl + name);
				FileInputStream fileInputStream = new FileInputStream(vaf);
				String fileName = vaf.getName();
				fileName = fileName.substring((fileName.lastIndexOf("/") + 1));
				mFile =  new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
				//String  url = ossService.uploadFileOss2(mFile);
				//certificateManagementDO.setUrl(url); //证书路径
				certificateManagementDO.setToUrl(mFile);
				certificateManagementDOS.add(certificateManagementDO);

			}
		//	System.out.println("长度是==="+certificateManagementDOS.size());
			List<ErrorCodeVo> list1De = new ArrayList<>();
			if(certificateManagementDOS.size()>0){
				List list1=new ArrayList();
				List list2=new ArrayList();
				list1.clear();
				list2.clear();
				for(CertificateManagementDO li :certificateManagementDOS){
					list1.add(li.getIdNumber());
					list2.add(li.getCertificateType());
				}

					Integer count=	certificateManagementService.countNumber(list1,list2);
					if(count>0){
						//	System.out.println("list1"+list1);
						//	System.out.println("list2"+list2);
						for(CertificateManagementDO li2 :certificateManagementDOS){
							//	System.out.println("姓名li.getName()"+li.getName());
							//	System.out.println("身份证li.getIdNumber()"+li.getIdNumber());
							StringBuilder sb = new StringBuilder();
							List list1s=new ArrayList();
							List list2s=new ArrayList();
							list1s.clear();
							list2s.clear();
							list1s.add(li2.getIdNumber());
							list2s.add(li2.getCertificateType());
							Integer counts=	certificateManagementService.countNumber(list1s,list2s);
							if(counts>0){
								//	System.out.println("姓名"+li.getName()  + "身份证 "+li.getIdNumber() + "存在重复数据 ");
								sb.append("姓名"+li2.getName()  + "身份证 "+li2.getIdNumber() + "存在重复数据，不进行导入");
								ErrorCodeVo errorCodeVo = new ErrorCodeVo();
								errorCodeVo.setErrorCode(sb.toString());
								list1De.add(errorCodeVo);
							}else {
								sb.append("姓名"+li2.getName()  + "身份证 "+li2.getIdNumber() + "成功导入数据============");
								ErrorCodeVo errorCodeVo = new ErrorCodeVo();
								errorCodeVo.setErrorCode(sb.toString());
								list1De.add(errorCodeVo);
								certificateManagementDOS1.add(li2);
							}
						}


						//return	ApiResult.fail("存在重复导入数据！");
					}else {
						certificateManagementDOS1=certificateManagementDOS;
					}


			}


			schoolApittController.testHandler(certificateManagementDOS1);

			deleteFile(new File(unzipFileUrl)); //删除解压后的证书文件

			if(list1De.size()>0){
				StringBuilder sb = new StringBuilder();
				int sizes=certificateManagementDOS.size()-certificateManagementDOS1.size();
				if(sizes>0){
					sb.append("成功导入数据条数为："+certificateManagementDOS1.size());
				}else {
					sb.append("成功导入数据条数为："+0+"条");
				}

				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setErrorCode(sb.toString());
				list1De.add(errorCodeVo);

				JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1De));
				//将list1存到缓存中
				EhCacheUtil.put("ManageMsg" + this.getUserId(), jsonArray);
				//	System.out.println(EhCacheUtil.get("ManageMsg"));
				deleteFile(new File(unzipFileUrl)); //删除解压后的证书文件
				return 	ApiResult.fail(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
			}

		} catch (IOException e) {

			throw new RuntimeException(e);
		}finally {
			try {
				deleteFile(new File(unzipFileUrl)); //删除解压后的证书文件
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return	ApiResult.success("成功导入"+fileNum+"条数据");
		//return Result.ok("成功导入"+fileNum+"条数据");
	}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importError")
	@ResponseBody
	@Transactional
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("证书导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("ManageMsg" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
		EhCacheUtil.remove("ManageMsg" + this.getUserId());
	}


	private static void deleteFile(File file) throws IOException {
		File[] files = file.listFiles();
		if (files!=null){//如果包含文件进行删除操作
			for (int i = 0; i <files.length ; i++) {
				if (!files[i].getName().contains("jy")) {
					if (files[i].isFile()) {
						//删除子文件
						files[i].delete();
					} else if (files[i].isDirectory()) {
						//通过递归的方法找到子目录的文件
						deleteFile(files[i]);
					}
					files[i].delete();//删除子目录
				}
			}
		}
	}










}
